﻿using Tycho.Runtime;
using Tycho.Utilities;
using Tycho.Transactions;

namespace Tycho.Peyote {
    public static class ResultObject {
        private static Symbol ValueSymbol = Environment.PeyoteNamespace.Get ("value");
        private static Symbol FormulaSymbol = Environment.PeyoteNamespace.Get ("formula");
        private static Symbol EvaluatorSymbol = Environment.PeyoteNamespace.Get ("evaluator");

        public static AnyObject Pattern = RuntimeModule.CreateStructure (FormulaSymbol, RuntimeModule.Null, ValueSymbol, RuntimeModule.Null);

        [TychoObject ("result")]
        public static AnyObject Prototype = RuntimeModule.CreatePrototype ();

        public static AnyObject Create(string formula, ITopLevel topLevel) {
            AnyObject res = RuntimeModule.CreatePrototype(Prototype);
            res.SetFormula (formula);
            res.SetEvaluator (topLevel);
            return res;
        }

        public static string GetFormula (this AnyObject self) {
            return self.GetProperty (FormulaSymbol).ExpectValue<string> ();
        }

        public static void SetFormula (this AnyObject self, string formula) {
            self.SetProperty (FormulaSymbol, formula);
        }

        public static ITopLevel GetEvaluator (this AnyObject self) {
            return self.GetProperty (EvaluatorSymbol).ExpectNative<ITopLevel> ();
        }

        public static void SetEvaluator (this AnyObject self, ITopLevel topLevel) {
            self.SetProperty (EvaluatorSymbol, RuntimeModule.CreateNative(topLevel));
        }

        public static AnyObject GetValue (this AnyObject self) {
            return self.GetProperty (ValueSymbol);
        }

        [TychoGetter2("result", "value")]
        public static AnyObject PrototypeGetValue (this AnyObject self) {
            ITopLevel topLevel = self.GetEvaluator();
            return topLevel.Evaluate(self.GetFormula());
        }
    }
}